import React, { useState, useEffect } from 'react';
import { Card, Input, Pagination, Select } from 'antd';
import axios from 'axios';
import { useParams } from 'react-router-dom';

const { Meta } = Card;
const { Option } = Select;


// const imageUrls = [
//   'https://pic1.zhimg.com/v2-c661740055d91606880283692e40720c_r.jpg',
//   'https://wallpaperm.cmcm.com/4700eaf249b71d56d95aff8ca94313fa.jpg',
//   'https://pic3.zhimg.com/v2-5523ed93593ee4c7fd97b972d0af92d3_r.jpg',
//   'https://pic1.zhimg.com/v2-3e2fe005af51c7636486d2a9a99cfb3e_r.jpg',
//   // ... 更多图片链接
// ];

// const getRandomImageUrl = () => {
//   const randomIndex = Math.floor(Math.random() * imageUrls.length);
//   return imageUrls[randomIndex];
// };
const calculateCP = (card) => {
  return Math.floor((card.attack * 2 + card.defense * 1.5 + card.health) / 3);
};

const CardInfo = () => {
  const { userId } = useParams();

  const [cards, setCards] = useState([]);
  const [filteredCards, setFilteredCards] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [sortOrder, setSortOrder] = useState('ascend');

  useEffect(() => {
    const fetchCards = async () => {
      setLoading(true);
      try {
        const response = await axios.post('http://localhost:3001/getUserCards', { userId: userId });
        const data = response.data.map(card => ({
          ...card,
          cp: calculateCP(card)
        }));
        setCards(data);
        setFilteredCards(data);
      } catch (error) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };
    fetchCards();
  }, [userId]);

  const handleSearch = (e) => {
    const term = e.target.value.toLowerCase();
    setSearchTerm(term);
    const filtered = cards.filter(card =>
      card.name.toLowerCase().includes(term) ||
      card.rarity.toLowerCase().includes(term) ||
      String(card.cp).includes(term)
    );
    setFilteredCards(filtered);
  };

  const handleSortChange = (value) => {
    setSortOrder(value);
    const sorted = [...filteredCards].sort((a, b) => {
      if (value === 'ascend') {
        return a.cp - b.cp;
      } else {
        return b.cp - a.cp;
      }
    });
    setFilteredCards(sorted);
  };

  const handlePageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  const paginatedCards = filteredCards.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <Input
          placeholder="Search by name, rarity or CP"
          value={searchTerm}
          onChange={handleSearch}
          style={{ width: 300, marginRight: 10 }}
        />
        <Select
          defaultValue="ascend"
          style={{ width: 120 }}
          onChange={handleSortChange}
        >
          <Option value="ascend">升序</Option>
          <Option value="descend">降序</Option>
        </Select>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
        {paginatedCards.map((card) => (
          <Card
            key={card.id}
            hoverable
            style={{
              width: 240,
              marginRight: 16,
              marginBottom: 16
            }}
            cover={<img alt="example" src={card.image_url} />}
          >
            <Meta
              title={card.name}
              description={
                <div>
                  <p>稀有等级: {card.rarity}</p>
                  <p>攻击力: {card.attack}</p>
                  <p>防御力: {card.defense}</p>
                  <p>生命值: {card.health}</p>
                  <p>战斗力: {card.cp}</p>
                </div>
              }
            />
          </Card>
        ))}
      </div>
      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={filteredCards.length}
        onChange={handlePageChange}
        style={{ marginTop: 20 }}
      />
    </div>
  );
};

export default CardInfo;
